package net.huashitong.Project.web;

import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.JqGrid;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Project.entity.NewProjects;
import net.huashitong.Project.entity.ProjectCollection;
import net.huashitong.Project.filter.NewProjectsFilter;
import net.huashitong.Project.filter.ProjectCollectionFilter;
import net.huashitong.Project.service.NewProjectsService;
import net.huashitong.Project.service.ProjectCollectionService;
import net.huashitong.node.service.NodeNewschedulesService;
import net.huashitong.oversee.entity.SupervisionTask;
import net.huashitong.oversee.filter.SupervisionTaskFilter;
import net.huashitong.oversee.service.SupervisionTaskService;
import net.huashitong.user.entity.BnpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/projectManageSuper")
public class ProjectManageController extends JsonBaseController {
    @Override
    protected String getView(String s) {
        return "/modules/projectManage/" + s;
    }

    @Autowired
    private NewProjectsService newProjectsService;
    @Autowired
    private NodeNewschedulesService nodeNewschedulesService;
    @Autowired
    private SupervisionTaskService taskService;
    @Autowired
    private ProjectCollectionService collectionService;


    @RequestMapping(method = RequestMethod.GET)
    public String initPage(HttpServletRequest request, Model model) {
        model.addAttribute("leftType", "项目管理");
        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        if (ObjectUtils.isBlank(bnpUser)) {
            return "/modules/login/login";
        }
        //待办任务个数
        int nodeCount = (int) WebUtils.getSessionAttribute(request, "nodeCount");
        SupervisionTaskFilter taskFilter = new SupervisionTaskFilter();
        taskFilter.setUserinfo(bnpUser.getPhone());
        taskFilter.setBranchType(bnpUser.getBranchType());
        taskFilter.setRole(bnpUser.getRole());
        taskFilter.setValid("1");
        int myTaskNum = taskService.getMissinTaskCount(taskFilter);
        WebUtils.setSessionAttribute(request, "myTaskNum", myTaskNum);
        int quetionNum = (int) WebUtils.getSessionAttribute(request, "quetionNum");
        model.addAttribute("user", bnpUser);
        model.addAttribute("nodeCount", nodeCount);
        model.addAttribute("myTaskNum", myTaskNum);
        model.addAttribute("quetionNum", quetionNum);
        return getView("query");
    }

    //===========================我的收藏============================
    /**
     * 我的收藏
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/myCollection",method = RequestMethod.GET)
    public String myCollection(HttpServletRequest request, Model model) {
        model.addAttribute("leftType", "我的收藏");
        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        if (ObjectUtils.isBlank(bnpUser)) {
            return "/modules/login/login";
        }
        //待办任务个数
        int nodeCount = (int) WebUtils.getSessionAttribute(request, "nodeCount");
        SupervisionTaskFilter taskFilter = new SupervisionTaskFilter();
        taskFilter.setUserinfo(bnpUser.getPhone());
        taskFilter.setBranchType(bnpUser.getBranchType());
        taskFilter.setRole(bnpUser.getRole());
        taskFilter.setValid("1");
        int myTaskNum = taskService.getMissinTaskCount(taskFilter);
        WebUtils.setSessionAttribute(request, "myTaskNum", myTaskNum);
        int quetionNum = (int) WebUtils.getSessionAttribute(request, "quetionNum");
        model.addAttribute("user", bnpUser);
        model.addAttribute("nodeCount", nodeCount);
        model.addAttribute("myTaskNum", myTaskNum);
        model.addAttribute("quetionNum", quetionNum);
        return getView("myCollection");
    }


    //初始化数据(我的收藏)
    @ResponseBody
    @RequestMapping(value = "/myCollection", method = RequestMethod.POST)
    public JqGrid myCollection(@ModelAttribute NewProjectsFilter filter, HttpServletRequest request, Model model) {
        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        String phone = bnpUser.getPhone();
        String branchType = bnpUser.getBranchType();
        String role = bnpUser.getRole();

        String collectUser = bnpUser.getSysId();
        //获取用户收藏
        ProjectCollectionFilter filter1 = new ProjectCollectionFilter();
        filter1.setCollectUser(collectUser);
        List<ProjectCollection> collections = collectionService.queryByFilter(filter1);
        List<String> projectIds = new ArrayList<>();
        for (ProjectCollection projectCollection : collections) {
            if(!projectIds.contains(projectCollection.getProjectId())){
                projectIds.add(projectCollection.getProjectId());
            }
        }

        if ("4".equals(branchType) || "2".equals(branchType) || "1".equals(branchType)) {
            //管理员或者审批部门（可查看所有项目）
        } else if ("0".equals(branchType) && "经办人".equals(role)) {
            //业主单位经办人
            filter.setContactPhone(phone);
        } else if ("0".equals(branchType) && "责任人".equals(role)) {
            //业主单位责任人
            filter.setOwnerUnitPersonPhone(phone);
        }
        if ("6".equals(branchType)) {
            //分管领导
            filter.setResPhone(phone);
        }
        //设置默认排序
        if (StringUtils.isBlank(filter.getPaging().getSortCol())) {
            filter.getPaging().setSortCol("sysId");
            filter.getPaging().setSortVal("desc");
        }
        filter.setSysids(projectIds);
        //进入督查的节点
        List<NewProjects> resList = newProjectsService.getProjectInfo4(filter);
        List<ProjectCollection> collectList = collectionService.queryAll();
        List<String> collectFlags = new ArrayList<>();
        for (ProjectCollection collection : collectList) {
            String projectId = collection.getProjectId();
            collectFlags.add(projectId + "-" + collectUser);
        }
        for (NewProjects newProjects : resList) {
            String projectId = newProjects.getSysId();
            String demo = projectId + "-" + collectUser;
            if(collectFlags.contains(demo)){
                newProjects.setCollectFlag(newProjects.getSysId());
            }else{
                newProjects.setCollectFlag("");
            }
        }


        List<SupervisionTask> tasks = taskService.query();
        Map<String, List<SupervisionTask>> taskMap = new HashMap<>();
        for (SupervisionTask task : tasks) {
            if (!taskMap.containsKey(task.getProjectId())) {
                List<SupervisionTask> list = new ArrayList<>();
                list.add(task);
                taskMap.put(task.getProjectId(), list);
            } else {
                List<SupervisionTask> list = taskMap.get(task.getProjectId());
                list.add(task);
                taskMap.put(task.getProjectId(), list);
            }
        }
        for (NewProjects project : resList) {
            List<SupervisionTask> list = taskMap.get(project.getSysId());
            if (ObjectUtils.isNotBlank(list) && list.size() > 0) {
                StringBuffer stringBuffer = new StringBuffer();
                for (int i = 0; i < list.size(); i++) {
                    if (i == 0) {
                        stringBuffer.append(list.get(i).getNodeId());
                    } else {
                        stringBuffer.append("、" + list.get(i).getNodeId());
                    }
                }
                project.setSupervisionNodes(stringBuffer.toString());
            }
        }
        return coverJqGrid(filter, resList);
    }

    //===========================我的收藏============================



    @RequestMapping("/filter")
    public String filter(@ModelAttribute SupervisionTaskFilter filter, Model model) {
        //项目列表中的责任单位
        List<String> resDepts = newProjectsService.getResDpetInAllProject();
        model.addAttribute("resDepts", resDepts);
        return getView("filter");
    }

    //初始化数据
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public JqGrid query(@ModelAttribute NewProjectsFilter filter, HttpServletRequest request, Model model) {
        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        String phone = bnpUser.getPhone();
        String branchType = bnpUser.getBranchType();
        String collectUser = bnpUser.getSysId();
        String role = bnpUser.getRole();
        if ("4".equals(branchType) || "2".equals(branchType) || "1".equals(branchType)) {
            //管理员或者审批部门（可查看所有项目）
        } else if ("0".equals(branchType) && "经办人".equals(role)) {
            //业主单位经办人
            filter.setContactPhone(phone);
        } else if ("0".equals(branchType) && "责任人".equals(role)) {
            //业主单位责任人
            filter.setOwnerUnitPersonPhone(phone);
        }
        if ("6".equals(branchType)) {
            //分管领导
            filter.setResPhone(phone);
        }
        //设置默认排序
        if (StringUtils.isBlank(filter.getPaging().getSortCol())) {
            filter.getPaging().setSortCol("sysId");
            filter.getPaging().setSortVal("desc");
        }
        //进入督查的节点
        List<NewProjects> resList = newProjectsService.getProjectInfo4(filter);
        List<ProjectCollection> collectList = collectionService.queryAll();
        List<String> collectFlags = new ArrayList<>();
        for (ProjectCollection collection : collectList) {
            String projectId = collection.getProjectId();
            collectFlags.add(projectId + "-" + collectUser);
        }
        for (NewProjects newProjects : resList) {
            String projectId = newProjects.getSysId();
            String demo = projectId + "-" + collectUser;
            if(collectFlags.contains(demo)){
                newProjects.setCollectFlag(newProjects.getSysId());
            }else{
                newProjects.setCollectFlag("");
            }
        }
        List<SupervisionTask> tasks = taskService.query();
        Map<String, List<SupervisionTask>> taskMap = new HashMap<>();
        for (SupervisionTask task : tasks) {
            if (!taskMap.containsKey(task.getProjectId())) {
                List<SupervisionTask> list = new ArrayList<>();
                list.add(task);
                taskMap.put(task.getProjectId(), list);
            } else {
                List<SupervisionTask> list = taskMap.get(task.getProjectId());
                list.add(task);
                taskMap.put(task.getProjectId(), list);
            }
        }
        for (NewProjects project : resList) {
            List<SupervisionTask> list = taskMap.get(project.getSysId());
            if (ObjectUtils.isNotBlank(list) && list.size() > 0) {
                StringBuffer stringBuffer = new StringBuffer();
                for (int i = 0; i < list.size(); i++) {
                    if (i == 0) {
                        stringBuffer.append(list.get(i).getNodeId());
                    } else {
                        stringBuffer.append("、" + list.get(i).getNodeId());
                    }
                }
                project.setSupervisionNodes(stringBuffer.toString());
            }
        }

        return coverJqGrid(filter, resList);
    }


    /**
     * 查看项目详情（主要是显示功能按钮）
     *
     * @param model
     * @param request
     * @param id
     * @return
     */
    @RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
    public String readLog(Model model, HttpServletRequest request, @PathVariable String id) {
        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        NewProjects project = newProjectsService.getById(id);
        model.addAttribute("user", bnpUser);
        model.addAttribute("project", project);
        return getView("detail");
    }

    @RequestMapping(value = "/editProject/{id}", method = RequestMethod.GET)
    public String editProject(Model model, HttpServletRequest request, @PathVariable String id) {
        NewProjects project = newProjectsService.getById(id);
        model.addAttribute("project", project);
        return getView("editProject");
    }

}
